package com.wsx.sky.sentinel.init;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.wsx.sky.sentinel.fisrt.UserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.sentinel.init.RuleManager
 * @Description: TODO
 * @date 2019/03/06
 */
public class RuleManager {


    public static void initRule() {
        List<FlowRule> rules = new ArrayList<>();
        //限流的规则配置
        FlowRule rule = new FlowRule();
        //限流的资源名称
        rule.setResource(UserService.USER_RS);
        //限流的阈值
        rule.setCount(UserService.USER_CT);
        //限流的类型，QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //被限制的app，default不区分调用者;{origin}针对特定的调用者，ContextUtil.entry(origin);other是除{origin}之外的
        rule.setLimitApp("default");
        //基于调用关系的流量控制，STRATEGY_DIRECT根据调用方限流；STRATEGY_RELATE根据关联流量限流；STRATEGY_CHAIN根据调用链入口
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
        //流量控制策略，CONTROL_BEHAVIOR_DEFAULT直接拒绝；CONTROL_BEHAVIOR_WARM_UP排队等待；CONTROL_BEHAVIOR_RATE_LIMITER均速器模式
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);

        List<DegradeRule> drules = new ArrayList<>();
        //熔断降级的规则配置
        DegradeRule drule = new DegradeRule();
        //资源名称
        drule.setResource(com.wsx.sky.sentinel.third.UserService.USER_RS);
        //时间阈值，单位ms，超过该时间进行准熔断状态
        drule.setCount(100);
        //熔断的时间窗口，单位为秒，
        drule.setTimeWindow(10);
        //熔断控制机制
        drule.setGrade(RuleConstant.DEGRADE_GRADE_RT);
        drules.add(drule);
        /**
         * DEGRADE_GRADE_RT：平均响应时间，当资源的平均响应时间超过count，再次请求5个，RT持续超过阈值，那么在下个timewindow内熔断
         * DEGRADE_GRADE_EXCEPTION_RATIO：异常比例，当资源请求的异常总数占通过数的阈值count，进入降级，在下个imewindow内熔断
         * DEGRADE_GRADE_EXCEPTION_COUNT：异常数，资源接近一分钟内的数量超过阈值进行熔断
         */
        DegradeRuleManager.loadRules(drules);


    }
}
